package jast;
import java.util.ArrayList;
import java.util.Set;
import org.antlr.v4.runtime.misc.MultiMap;
import org.antlr.v4.runtime.misc.OrderedHashSet;
import path.BranchNode;

public class Graph {
	//org.antlr.v4.runtime.misc: OrderedHashSet,MultiMap
	Set<BranchNode> nodes = new OrderedHashSet<BranchNode>(); // list of nodes
	MultiMap<BranchNode, BranchNode> edges = 
			new MultiMap<BranchNode, BranchNode>();
	public void edge(BranchNode source, BranchNode target) {
		edges.map(source, target);
	}
	ArrayList<String> edgeList = new ArrayList<String>();

	public String toDOT(){
		StringBuilder buf = new StringBuilder(); 
		buf.append("digraph G {\n");
		buf.append(" ranksep=.25;\n"); 
		buf.append(" edge [arrowsize=.5]\n"); 
		buf.append(" node [shape=circle, fontsize=12, fixedsize=true, height=.45];\n"); 
		buf.append(" "); 
		for (BranchNode node : nodes) { 
			// print all nodes first 
			buf.append(node.id); 
			buf.append("; "); 
		} 
		buf.append("\n"); 
		for (BranchNode src : edges.keySet()) { 
			for (BranchNode trg : edges.get(src)) {
				String edge = " "+src.id+" -> "+trg.id+";\n";
				//去重
				if(!edgeList.contains(edge))
					edgeList.add(edge);
			}
		}
		for(int i=0;i<edgeList.size();i++)
			buf.append(edgeList.get(i));
		buf.append("}\n"); 
		return buf.toString();
	}
}